package com.sgb.packers.view.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.link.entity.ProjectTakeEntity;
import com.sgb.link.router.PathTeam;
import com.sgb.packers.R;
import com.sgb.packers.databinding.PackersFragmentGetJobBinding;
import com.sgb.packers.entity.PressDayCalendarEntity;
import com.sgb.packers.entity.ProjectEntity;
import com.sgb.packers.utils.SchemeUtils;
import com.sgb.packers.view.activity.AddProjectActivity;
import com.sgb.packers.viewmodel.GetJobViewModel;
import com.sgb.younghow.calendarview.CalendarView;
import com.swgk.core.common.base.TeamBaseFragment;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.interfaces.DialogClick;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.MapUtils;
import com.swgk.core.util.NewDialogHelper;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author younghow
 * @date 2021/9/23
 * description:
 */
public class GetJobFragment extends TeamBaseFragment<GetJobViewModel, PackersFragmentGetJobBinding> implements CalendarView.OnCalendarSelectListener, CalendarView.OnCalendarInterceptListener, CalendarView.OnMonthChangeListener {

    private TimePickerView timeEndPicker;
    private List<ProjectEntity> mProject;
    private int mProjectPopPosition;
    private String mAddProjectName;
    private String projectNo;
    private int year,month;
    private boolean isNew;

    public static GetJobFragment newInstance(List<ProjectEntity> list) {
        GetJobFragment getJobFragment = new GetJobFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("project", (Serializable) list);
        getJobFragment.setArguments(bundle);
        return getJobFragment;
    }

    @Override
    protected Class<GetJobViewModel> createVM() {
        return GetJobViewModel.class;
    }

    @Override
    protected void initView() {

        initListener();
        initLiveData();
    }

    private void initLiveData() {
        mViewModel.mGetProjectLiveData.observe(getViewLifecycleOwner(), projectEntities -> {
            mProject = projectEntities;
            if (mProject != null && mProject.size() > 0) {
                OptionsPickerView mProjectPop = new OptionsPickerBuilder(getContext(), (options1, options2, options3, view) -> {
                    mBinding.tvProjectName.setText(mProject.get(options1).getProjectName());
                    projectNo = mProject.get(options1).getNo();
                    mProjectPopPosition = options1;

                    String month1 = month >= 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
                    pressDay(String.valueOf(year), month1);
                    projectTake(String.valueOf(year), month1);
                }).setCancelColor(ContextCompat.getColor(getContext(), R.color.color_666666)).setTitleColor(ContextCompat.getColor(getContext(), R.color.color_969696)).build();
                mProjectPop.setPicker(mProject);
                mProjectPop.setSelectOptions(mProjectPopPosition);
                mProjectPop.setTitleText("选择项目");
                if (!isNew){
                    mProjectPop.show();
                }else {
                    projectNo = projectEntities.get(0).getNo();
                    String month1 = month >= 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
                    pressDay(String.valueOf(year),month1);
                    projectTake(String.valueOf(year),month1);
                }
            } else {
                MToast.showToast(getContext(), "没有项目");
            }
        });

        mViewModel.mAddProjectLiveData.observe(getViewLifecycleOwner(), aBoolean -> {
            mViewModel.getProject(new MapUtils().pair2Map(Pair.create("type", 1)));
            isNew = true;
            mProjectPopPosition = 0;
            mBinding.calendarView.clearSchemeDate();
            mBinding.tvProjectName.setText(mAddProjectName);
        });

        mViewModel.mPressDayLiveData.observe(getViewLifecycleOwner(), pressDayCalendarEntities -> {
            Map<String, com.sgb.younghow.calendarview.Calendar> map = new HashMap<>();
            for (PressDayCalendarEntity pressDayCalendarEntity : pressDayCalendarEntities) {
                String[] split = pressDayCalendarEntity.getWorkDate().split("-");
                if (TextUtils.isEmpty(pressDayCalendarEntity.getCalendarInfo())) {
                    continue;
                }

                if (pressDayCalendarEntity.getCalendarInfo().contains("个工")) {
                    map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFef4033, pressDayCalendarEntity.getCalendarInfo()).toString(),
                            SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFef4033, pressDayCalendarEntity.getCalendarInfo()));
                } else if (pressDayCalendarEntity.getCalendarInfo().contains("包工")) {
                    map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFED9E13, pressDayCalendarEntity.getCalendarInfo()).toString(),
                            SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFED9E13, pressDayCalendarEntity.getCalendarInfo()));
                } else if (pressDayCalendarEntity.getCalendarInfo().contains("加班")) {
                    map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()).toString(),
                            SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()));
                } else if (pressDayCalendarEntity.getCalendarInfo().contains("小时")){
                    map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()).toString(),
                            SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()));
                }
            }
            mBinding.calendarView.setSchemeDate(map);
        });

        mViewModel.projectTakeLiveData.observe(getViewLifecycleOwner(), projectTakeEntity -> {
            if (projectTakeEntity.getPointWorkStatisticsList() == null || projectTakeEntity.getPointWorkStatisticsList().size() == 0) {
                mBinding.tvWorkNumber.setText("0个工");
                mBinding.tvAddWorkNumber.setText("0小时");
                mBinding.tvHour.setText("0小时");
            }

            if (projectTakeEntity.getWrapWorkStatisticsList() != null && projectTakeEntity.getWrapWorkStatisticsList().size() == 0) {
                mBinding.tvContractWorkNumber.setText("0笔");
            }

            if (projectTakeEntity.getPointWorkStatisticsList() != null && projectTakeEntity.getPointWorkStatisticsList().size() > 0) {
                mBinding.tvWorkNumber.setText(String.format(Locale.CHINA, "%.1f个工", projectTakeEntity.getPointWorkStatisticsList().get(0).getWorkDayAll()));
                mBinding.tvAddWorkNumber.setText(String.format(Locale.CHINA, "%.1f小时", projectTakeEntity.getPointWorkStatisticsList().get(0).getWorkOverHourAll()));
                mBinding.tvHour.setText(String.format(Locale.CHINA, "%.1f小时", projectTakeEntity.getPointWorkStatisticsList().get(0).getWorkHourAll()));
            }

            if (projectTakeEntity.getWrapWorkStatisticsList() != null && projectTakeEntity.getWrapWorkStatisticsList().size() > 0) {
                mBinding.tvContractWorkNumber.setText(String.format(Locale.CHINA, "%.0f笔", projectTakeEntity.getWrapWorkStatisticsList().get(0).getWrapWorkNum()));
            }
        });

        AddProjectActivity addProjectActivity = (AddProjectActivity) getActivity();
        if (addProjectActivity != null) {
            addProjectActivity.nameLiveData.observe(getViewLifecycleOwner(), s ->{
                mBinding.tvProjectName.setText(s);
            });

            addProjectActivity.newLiveData.observe(getViewLifecycleOwner(), new Observer<String>() {
                @Override
                public void onChanged(String s) {
                    mBinding.tvProjectName.setText(s);
                    mViewModel.getProject(new MapUtils().pair2Map(Pair.create("type", 1)));
                    isNew = true;
                    mProjectPopPosition = 0;
                    mBinding.calendarView.clearSchemeDate();
                }
            });
        }
    }

    private void initListener() {
        mBinding.tvGetWork.setOnClickListener(this);
        mBinding.tvTakeJobDate.setOnClickListener(this);
        mBinding.tvProjectName.setOnClickListener(this);
        mBinding.tvNewProject.setOnClickListener(this);
        mBinding.calendarView.setOnMonthChangeListener(this);
        mBinding.ivTakeNoteTurnover.setOnClickListener(this);
        mBinding.ivTakeNoteStatistics.setOnClickListener(this);
        mBinding.ivProjectManager.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            mProject = (List<ProjectEntity>) getArguments().getSerializable("project");
        }

        if (mProject != null && mProject.size() > 0) {
            mBinding.tvProjectName.setText(mProject.get(0).getProjectName());
            projectNo = mProject.get(0).getNo();
        }

        mBinding.tvTakeJobDate.setText(DateUtils.date2Timestamp(System.currentTimeMillis()));

        mBinding.calendarView.setOnCalendarSelectListener(this);

        mBinding.calendarView.setOnCalendarInterceptListener(this);

        String[] split = DateUtils.timestamp2DateNumber(System.currentTimeMillis());
        pressDay(split[0], split[1]);

        projectTake(split[0], split[1]);

        mBinding.calendarView.setWeeColor(0,0xff666666);
        mBinding.calendarView.setRange(2000, 1, 1, Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
    }

    private void projectTake(String year, String month) {
        Map<String, Object> objectMap = new HashMap<>(7);
        objectMap.put("dimension", "1");
        objectMap.put("month", month);
        objectMap.put("projectNo", projectNo);
        objectMap.put("recordType", "1");
        objectMap.put("year", year);
        mViewModel.projectTake(objectMap);
    }

    @Override
    protected int layoutId() {
        return R.layout.packers_fragment_get_job;
    }

    @Override
    protected void onMultiClick(View v) {
        super.onMultiClick(v);
        if (v.getId() == R.id.tv_get_work) {
            ActivityJump.startActivity(PathTeam.PersonGetWorkActivity, Pair.create("projectName", mBinding.tvProjectName.getText().toString()), Pair.create("projectNo", projectNo));
        } else if (v.getId() == R.id.tv_take_job_date) {
            Calendar day = Calendar.getInstance();
            if (timeEndPicker == null) {
                timeEndPicker = new TimePickerBuilder(getContext(), (date, v1) -> {
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTime(date);
                    cal1.set(Calendar.HOUR_OF_DAY, 23);
                    cal1.set(Calendar.MINUTE, 59);
                    cal1.set(Calendar.SECOND, 59);
                    pressDay(DateUtils.timestamp2DateNumber(date)[0], DateUtils.timestamp2DateNumber(date)[1]);
                    mBinding.calendarView.scrollToCalendar(Integer.parseInt(DateUtils.timestamp2DateNumber(date)[0]), Integer.parseInt(DateUtils.timestamp2DateNumber(date)[1]), 1);

                    mBinding.tvTakeJobDate.setText(DateUtils.date2Timestamp(date));
                }).setTitleText("选择年月").setType(new boolean[]{true, true, false, false, false, false}).setRangDate(null, day).setTitleColor(ContextCompat.getColor(getContext(), R.color.color_969696)).setCancelColor(ContextCompat.getColor(getContext(), R.color.color_666666)).build();
            }

            timeEndPicker.show();
        } else if (v.getId() == R.id.tv_project_name) {
            isNew = false;
            mViewModel.getProject(new MapUtils().pair2Map(Pair.create("type", 1)));
        } else if (v.getId() == R.id.tv_new_project) {
            RoundCornerDialog newDialogHelper = new NewDialogHelper<String>(getContext())
                    .editDialog(false, true, "新建项目", "请输入项目名称", "确定", "取消")
                    .setDialogClick(new DialogClick<String>() {
                        @Override
                        public void confirmClick(String s, Dialog dialog) {
                            if (TextUtils.isEmpty(s)){
                                MToast.showToast(getContext(),"请输入项目名称");
                                return;
                            }
                            boolean haveProject = false;
                            mAddProjectName = s;
                            if (mProject != null && mProject.size() > 0) {
                                for (ProjectEntity projectEntity : mProject) {
                                    if (projectEntity.getProjectName().equals(s)) {
                                        haveProject = true;
                                        break;
                                    }
                                }
                            }

                            if (haveProject) {
                                MToast.showToast(getContext(), "项目名称重复，请重新输入");
                            } else {
                                mViewModel.addProject(new MapUtils().pair2Map(Pair.create("projectName", s), Pair.create("type", 1)));
                                dialog.cancel();
                            }
                        }
                    })
                    .build();
            newDialogHelper.show();
        } else if (v.getId() == R.id.iv_take_note_turnover) {
            ActivityJump.startActivity(PathTeam.WorkAccountActivity, Pair.create("projectName", mBinding.tvProjectName.getText().toString()), Pair.create("projectNo", projectNo), Pair.create("position", mProjectPopPosition));
        } else if (v.getId() == R.id.iv_take_note_statistics) {
            ActivityJump.startActivity(PathTeam.WorkStatisticsActivity, Pair.create("projectName", mBinding.tvProjectName.getText().toString()), Pair.create("projectNo", projectNo));
        } else if (v.getId() == R.id.iv_project_manager) {
            ActivityJump.startActivityForResult(getActivity(),1,PathTeam.ProjectManagerActivity, Pair.create("position", mProjectPopPosition));
        }
    }

    @Override
    public void onCalendarOutOfRange(com.sgb.younghow.calendarview.Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(com.sgb.younghow.calendarview.Calendar calendar, boolean isClick) {
        year = calendar.getYear();
        month = calendar.getMonth();
        if (isClick && !calendar.hasScheme()) {
            ActivityJump.startActivity(PathTeam.PersonGetWorkActivity, Pair.create("projectName", mBinding.tvProjectName.getText().toString())
                    , Pair.create("projectNo", projectNo), Pair.create("year", calendar.getYear()), Pair.create("month", calendar.getMonth()), Pair.create("day", calendar.getDay()));
        } else if (isClick && calendar.hasScheme()) {
            ActivityJump.startActivity(PathTeam.RecordWorkAccountBookActivity, Pair.create("projectName", mBinding.tvProjectName.getText().toString())
                    , Pair.create("projectNo", projectNo), Pair.create("year", calendar.getYear()), Pair.create("month", calendar.getMonth()), Pair.create("day", calendar.getDay()));
        }
    }

    @Override
    public boolean onCalendarIntercept(com.sgb.younghow.calendarview.Calendar calendar) {
        return calendar.getYear() > mBinding.calendarView.getCurYear() ||
                calendar.getMonth() > mBinding.calendarView.getCurMonth() ||
                (calendar.getMonth() == mBinding.calendarView.getCurMonth() &&
                        calendar.getDay() > mBinding.calendarView.getCurDay());
    }

    @Override
    public void onCalendarInterceptClick(com.sgb.younghow.calendarview.Calendar calendar, boolean isClick) {

    }

    public void pressDay(String year, String month) {
        Map<String, Object> map = new HashMap<>();
        map.put("month", month);
        map.put("projectNo", projectNo);
        map.put("type", 1);
        map.put("year", year);
        mViewModel.pressDay(map);
    }

    @Override
    public void onMonthChange(int year, int month) {
        mBinding.tvTakeJobDate.setText(String.format(Locale.CHINA, "%d年%d月", year, month));
        String month1 = month >= 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
        pressDay(String.valueOf(year), month1);
        projectTake(String.valueOf(year), month1);
    }

    @Override
    public void onResume() {
        super.onResume();
        String month1 = month >= 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
        pressDay(String.valueOf(year), month1);
        projectTake(String.valueOf(year), month1);
    }
}